package com.woniu.util;

import com.nimbusds.jose.JWSObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Map;

public class UserContext {
    public static Integer getUserId() throws ParseException {

        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String jwt = request.getHeader("token");
        JWSObject jwsObject = JWSObject.parse(jwt); //反序列化方法
        Map<String, Object> userMap = jwsObject.getPayload().toJSONObject();
        Long userId = (Long)userMap.get("id");
        return userId.intValue();
//        String jwt = request.getHeader("token");
//        return JWTUtil.getUseId(jwt);
    }
}
